package com.fingard.util;

import com.alibaba.fastjson.JSON;
import com.fingard.constant.DecimalFormat2;
import com.fingard.constant.Format;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.spdb01.SPDB01Base;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.AcroFields.FieldPosition;
import com.itextpdf.text.pdf.parser.FilteredTextRenderListener;
import com.itextpdf.text.pdf.parser.LocationTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import com.itextpdf.text.pdf.parser.RegionTextRenderFilter;
import com.itextpdf.text.pdf.parser.RenderFilter;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
import com.kayak.request.PaymentRequest;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfMargins;

import com.fingard.FGBiz;
import org.apache.pdfbox.util.PDFTextStripperByArea;
import sun.misc.BASE64Decoder;

import java.awt.Dimension;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.util.PDFTextStripper;

/**
 * Created by marlon on 2018/3/16. 利用模板生成pdf
 */
public class PdfGenerateUtil extends DirectBase {

	public static BASE64Decoder decoder;

	/**
	 * @param templatePath 模板路径
	 * 	 * @param newPDFPath   生成的新文件路径
	 * 	 * @param formInfoMap  填入模板数据
	 */
	public static String fillTemplate(String templatePath, String newPDFPath, Map<String, String> formInfoMap) {
		PdfReader reader=null;
		FileOutputStream out =null;
		ByteArrayOutputStream bos =null;
		PdfStamper stamper;
		try {
			File batFile = new File(newPDFPath);
			if (!batFile.getParentFile().exists()) {
				batFile.getParentFile().mkdirs();
			}
			out = new FileOutputStream(newPDFPath);// 输出流
			reader = new PdfReader(templatePath);// 读取pdf模板
			bos = new ByteArrayOutputStream();
			stamper = new PdfStamper(reader, bos);
			AcroFields form = stamper.getAcroFields();
			BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			for (String map : formInfoMap.keySet()) {
				form.setFieldProperty(map, "textfont", bfChinese, null);
				form.setField(map, formInfoMap.get(map));
			}
			//System.out.println("------------------"+formInfoMap.get("Remark"));
			System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
					"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
			stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
			stamper.close();
			Document doc = new Document();
			PdfCopy copy = new PdfCopy(doc, out);
			doc.open();
			PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
			copy.addPage(importPage);
			doc.close();
			return "true";
		} catch (IOException e) {
			return LogHelper.getStackTrace(e);
		} catch (DocumentException e) {
			return LogHelper.getStackTrace(e);
		}finally{
			if(bos!=null){
				try {
					bos.close();
				} catch (IOException e) {
					FGBiz.limitMsg.exception("PdfGenerateUtil", e);
				}
			}
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					FGBiz.limitMsg.exception("PdfGenerateUtil", e);
				}
			}
			if(reader!=null){
				reader.close();
			}
		}
	}

	/**
	 * 将base64编码转换成PDF
	 *
	 * @param base64sString
	 * @param newFilePath   "/home/amarsoft/test.pdf"
	 *                      1.使用BASE64Decoder对编码的字符串解码成字节数组
	 *                      2.使用底层输入流ByteArrayInputStream对象从字节数组中获取数据；
	 *                      3.建立从底层输入流中读取数据的BufferedInputStream缓冲输出流对象；
	 *                      4.使用BufferedOutputStream和FileOutputSteam输出数据到指定的文件中
	 */
	public static String base64StringToPDF(String newFilePath, String base64sString) {
		String returnStr = "";
		BufferedInputStream bin = null;
		FileOutputStream fout = null;
		BufferedOutputStream bout = null;
		ByteArrayInputStream bais = null;
		try {
			// 将base64编码的字符串解码成字节数组
			byte[] bytes = decoder.decodeBuffer(base64sString);
			// apache公司的API
			// byte[] bytes = Base64.decodeBase64(base64sString);
			// 创建一个将bytes作为其缓冲区的ByteArrayInputStream对象
			bais = new ByteArrayInputStream(bytes);
			// 创建从底层输入流中读取数据的缓冲输入流对象
			bin = new BufferedInputStream(bais);
			// 指定输出的文件
			File file = new File(newFilePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (file.exists()) {
				file.delete();
			}
			// 创建到指定文件的输出流
			fout = new FileOutputStream(file);
			// 为文件输出流对接缓冲输出流对象
			bout = new BufferedOutputStream(fout);

			byte[] buffers = new byte[1024];
			int len = bin.read(buffers);
			while (len != -1) {
				bout.write(buffers, 0, len);
				len = bin.read(buffers);
			}
			// 刷新此输出流并强制写出所有缓冲的输出字节，必须这行代码，否则有可能有问题
			bout.flush();
			returnStr = "true";
		} catch (IOException e) {
			returnStr = e.getMessage();
		} finally {
			try {
				bais.close();
				bin.close();
				fout.close();
				bout.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return returnStr;
	}

    private static TransIDHelper idHelper = new TransIDHelper(1, 999);

    public static void main(String[] args) throws Exception {


		String[] params = {"打印申请人:", "业务流水号", "交易时间", "主机流水号", "备注", "全国统一服务电话", "交易金额：", "客户电子回单（", "） 防伪码", "摘要：", "回单编号", "户名：", "本凭证作为", " 账号:", "开户银行:", "业务种类", "业务渠道", "防伪码：", "业务类型","账号:"};
		@SuppressWarnings("unchecked")
		List<String> fileNames = PdfGenerateUtil.splitPDF("E:\\333\\331001181012010000681520191024.pdf", params);
        //String[] art = new String[]{"","111","3333"};
        System.out.println(fileNames);

		//String cont = getPdfTextPosition(path,"Summary");
		//System.out.println(cont);
		/*
		 * Map<String, String> formInfoMap = new ConcurrentHashMap<String, String>();
		 * 
		 * // 模板路径 String templatePath = "C:/Users/dell/Desktop/we.pdf"; // 生成的新文件路径
		 * String newPDFPath = "C:/Users/dell/Desktop/12.pdf"; formInfoMap.put("1",
		 * "121212"); formInfoMap.put("2", "232"); formInfoMap.put("3", "FR地方");
		 * formInfoMap.put("4", "23"); System.out.println(fillTemplate(templatePath,
		 * newPDFPath, formInfoMap));
		 */
	}

	public static String getPdfFileText(String fileName) throws IOException {
		PdfReader reader = new PdfReader(fileName);
		PdfReaderContentParser parser = new PdfReaderContentParser(reader);
		StringBuffer buff = new StringBuffer();
		TextExtractionStrategy strategy;
		for (int i = 1; i <= reader.getNumberOfPages(); i++) {
			strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
			buff.append(strategy.getResultantText());
		}
		return buff.toString();
	}

	/*
	 * 获取pdf内表单内容
	 */
	public static String getPdfTextPosition(String filePath, String field) throws Exception {
		PdfReader reader = null;
		String str = "";
		try {
			reader = new PdfReader(filePath);
			AcroFields fields = reader.getAcroFields();
			List<FieldPosition> pos = fields.getFieldPositions(field);
			FieldPosition pitem = pos.get(0);
			Rectangle pRectangle = pitem.position;
			float[] p = { pRectangle.getLeft(), pRectangle.getBottom(), pRectangle.getRight(), pRectangle.getTop() };
			Rectangle rect = new Rectangle(p[0], p[1], p[2], p[3]);
			PdfPTable table = new PdfPTable(p);
			table.toString();
			RenderFilter regionFilter = new RegionTextRenderFilter(rect);
			TextExtractionStrategy strategys = new FilteredTextRenderListener(new LocationTextExtractionStrategy(),
					regionFilter);
			str = PdfTextExtractor.getTextFromPage(reader, 1, strategys);
			System.out.println(str);
			reader.close();
		} catch (Exception e) {
			reader.close();
		}

		return str;
	}

	public static String readFileOfPDF(String pdfName) throws IOException {
		String context = null;
		File file = new File(pdfName);// 创建一个文件对象
		FileInputStream infile = null;
		PDDocument pdfdocument = null;
		try {
			infile = new FileInputStream(pdfName);// 创建一个文件输入流
			// 新建一个PDF解析器对象
			PDFParser parser = new PDFParser(infile);
			// 对PDF文件进行解析
			parser.parse();
			// 获取解析后得到的PDF文档对象
			pdfdocument = parser.getPDDocument();
			// 新建一个PDF文本剥离器
			PDFTextStripper stripper = new PDFTextStripper();
			// 从PDF文档对象中剥离文本
			context = stripper.getText(pdfdocument);
			pdfdocument.close();
		} catch (Exception e) {
			System.out.println("读取PDF文件" + file.getAbsolutePath() + "失败！" + e.getMessage());
		} finally {
			if (pdfdocument != null) {
				pdfdocument.close();
			}
			if (infile != null) {
				try {
					infile.close();
				} catch (IOException e1) {
				}
			}
		}
		return context;
	}

	/**
	 * 按页分割PDF
	 * 
	 * @param pdfFile
	 * @return
	 * @throws Exception
	 */
	public static List<String> splitPDF(String pdfFile, String[] params) throws Exception {
		// 设置默认工厂类
		System.setProperty("org.apache.commons.logging.LogFactory", "org.apache.commons.logging.impl.LogFactoryImpl");
		//TODO ms
		// 设置日志打印类
//		LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
//		//设置默认日志级别
//		LogFactory.getFactory().setAttribute("org.apache.commons.logging.simplelog.defaultlog", "error");
		Document document = null;
		PdfCopy copy = null;
		String content = null;
		File desFile = new File(pdfFile);
		try {
			PdfReader reader = new PdfReader(pdfFile);
			int n = reader.getNumberOfPages();
			List<String> savepaths = new ArrayList<String>();
			int a = pdfFile.lastIndexOf(".pdf");
			String staticpath = pdfFile.substring(0, a) + File.separator
					+ desFile.getName().substring(0, desFile.getName().lastIndexOf(".pdf"));
			File savedes = new File(staticpath);
			if (!savedes.exists()) {
				savedes.mkdirs();
			}
			List<String> names = new ArrayList<String>();
			for (int i = 1; i <= n; i++) {
				String savepath = staticpath + "_" + i + ".pdf";
				savepaths.add(savepath);

				document = new Document(reader.getPageSize(1));
				copy = new PdfCopy(document, new FileOutputStream(savepath));
				document.open();
				document.newPage();
				PdfImportedPage page = copy.getImportedPage(reader, i);
				copy.addPage(page);
				document.close();
				File file = new File(savepath);

				String path = file.getParent();

				// 判断每页是否包含多个pdf
				content = readFileOfPDF(savepath);
				int count = count(content, (params[0]));
				// 无回单
				if (count == 0) {
					return null;
				}
				if (count > 1) {
					String s_path = "";
					if(params.length > 14) {
						s_path = splitFile(savepath, 3);
					}else {
						s_path = splitFile(savepath, count);
					}
					List<String> indexName = splitPDFByIndex(s_path, path, params, count);
					File deleFile = new File(s_path);
					if (deleFile.exists()) {
						deleFile.delete();
					}
					names.addAll(indexName);
				} else {
					if (params.length > 10) {
						List<String> indexName = splitPDFByIndex(savepath, path, params, count);
						names.addAll(indexName);
					} else {
						String tranDate = "";
						if (count(content, params[8]) > 0) {
							tranDate = content
									.substring(content.indexOf(params[8]) + params[8].length(),
											content.indexOf(params[8]) + params[8].length() + 20)
									.substring(0, 10).trim().replace("/", "-").replace("/", "-");
						} else {
							if(count(content, params[7]) > 0) {								
								tranDate = content
										.substring(content.indexOf(params[6]) + params[6].length(),
												content.indexOf(params[7]))
										.substring(0, 11).trim().replace("年", "-").replace("月", "-").replace("日", "");
							}else {
								tranDate = content
										.substring(content.indexOf(params[6]) + params[6].length(),content.indexOf(params[6]) + params[6].length() + 12)
										.substring(0, 11).trim().replace("年", "-").replace("月", "-").replace("日", "");
							}
						}
						if (count(content, params[1]) > 1) {
							content = content.split(params[0])[1];
						}
						// file.renameTo(new File(path + File.separator + tranSeqNo +"_" + fileName));
                        String tranSeqNo = content
								.substring(content.indexOf(params[1]) + params[1].length(), content.indexOf(params[2]))
								.trim().replace("-", "") + ".pdf";
						String newFile = path + File.separator + tranDate + "_" + tranSeqNo;
						createPDF(savepath,newFile);
						names.add(tranDate + "_" + tranSeqNo);
					}
				}

			}
			desFile.delete();
			return names;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} catch (DocumentException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (document != null) {
				document.close();
			}
		}
	}

	/*
	 * public static String splitFile(String filepath,int index) throws Exception {
	 * PDDocument outdoc = new PDDocument(); PDDocument doc =
	 * PDDocument.load(filepath); PDPage page = (PDPage)
	 * doc.getDocumentCatalog().getAllPages().get(0);
	 * 
	 * PDRectangle cropBox = page.getBleedBox(); float upperRightY =
	 * cropBox.getUpperRightY(); float lowerLeftY = cropBox.getLowerLeftY();
	 * 
	 * cropBox.setUpperRightY((float) (upperRightY / 2.6));
	 * cropBox.setLowerLeftY(lowerLeftY); page.setCropBox(cropBox);
	 * outdoc.importPage(page);
	 * 
	 * 
	 * cropBox.setUpperRightY((float) (upperRightY / 2.6));
	 * cropBox.setLowerLeftY(lowerLeftY); page.setCropBox(cropBox);
	 * outdoc.importPage(page);
	 * 
	 * cropBox.setUpperRightY((float) (upperRightY / 2.6));
	 * cropBox.setLowerLeftY(lowerLeftY); page.setCropBox(cropBox);
	 * outdoc.importPage(page); String path =
	 * filepath.substring(0,filepath.length()-4)+"_"+index+".pdf";
	 * outdoc.save(path); outdoc.close();
	 * 
	 * 
	 * doc.close(); return path; }
	 */

	public static String splitFile(String filepath, int index) throws Exception {
		PDDocument outdoc = null;
		PDDocument doc = null;
		try {
			outdoc = new PDDocument();
			doc = PDDocument.load(filepath);
			PDPage page = (PDPage) doc.getDocumentCatalog().getAllPages().get(0);
			if (index == 2) {

				PDRectangle cropBox = page.getArtBox();
				float upperRightY = cropBox.getUpperRightY();
				float lowerLeftY = cropBox.getLowerLeftY();
				cropBox.setLowerLeftY(upperRightY / 2);
				page.setCropBox(cropBox);
				outdoc.importPage(page);

				cropBox = page.getCropBox();
				cropBox.setUpperRightY(upperRightY / 2);
				cropBox.setLowerLeftY(lowerLeftY);
				page.setCropBox(cropBox);
				outdoc.importPage(page);
			} else {
				PDRectangle cropBox = page.getArtBox();
				float upperRightY = cropBox.getUpperRightY();
				float lowerLeftY = cropBox.getLowerLeftY();
				float upperRightX = cropBox.getUpperRightX();
				float lowerLeftX = cropBox.getLowerLeftX();
				cropBox.setUpperRightY((float) (upperRightY / 2.4));
				cropBox.setLowerLeftY((float) (lowerLeftY / 2.2));
				cropBox.setLowerLeftX((float) (lowerLeftX * 1.2));
				cropBox.setUpperRightX((float) (upperRightX * 1.2));
				page.setCropBox(cropBox);
				outdoc.importPage(page);

				cropBox = page.getCropBox();
				cropBox.setUpperRightY((float) (upperRightY / 1.35));
				cropBox.setLowerLeftY((float) (upperRightY / 2.41));
				page.setCropBox(cropBox);
				outdoc.importPage(page);

				cropBox = page.getCropBox();
				cropBox.setUpperRightY((float) (upperRightY * 1.2));
				cropBox.setLowerLeftY((float) (upperRightY / 1.35));
				page.setCropBox(cropBox);
				outdoc.importPage(page);
			}
			String path = filepath.substring(0, filepath.length() - 4) + "_" + index + ".pdf";
			outdoc.save(path);
			doc.close();
			outdoc.close();
			return path;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (outdoc != null) {
				outdoc.close();
			}
			if (doc != null) {
				doc.close();
			}
		}
	}

	public static int count(String text, String sub) {
		int count = 0, start = 0;
		while ((start = text.indexOf(sub, start)) >= 0) {
			start += sub.length();
			count++;
		}
		return count;
	}

	/**
	 * 按页分割PDF
	 * 
	 * @param pdfFile
	 * @return
	 * @throws IOException
	 */
	public static List<String> splitPDFByIndex(String pdfFile, String path, String[] params, int index)
			throws IOException {
		Document document = null;
		PdfCopy copy = null;
		FileOutputStream output = null;
		PdfReader reader = null;
		try {
			Rectangle pageSize = new Rectangle(216f, 720f);
			reader = new PdfReader(pdfFile);
			int n = reader.getNumberOfPages();
			List<String> savepaths = new ArrayList<String>();
			int a = pdfFile.lastIndexOf(".pdf");
			String staticpath = pdfFile.substring(0, a);
			List<String> names = new ArrayList<String>();
			for (int i = 1; i <= n; i++) {
				String savepath = staticpath + "_" + i + ".pdf";
				savepaths.add(savepath);
				document = new Document(pageSize);
				output = new FileOutputStream(savepath);
				copy = new PdfCopy(document, output);
				document.open();
				document.setMargins(180, 72, 108, 72);
				document.setMarginMirroringTopBottom(true);
				document.newPage();
				PdfImportedPage page = copy.getImportedPage(reader, i);
				copy.addPage(page);
				document.close();
				output.close();
				String content = readFileOfPDF(savepath).replaceAll("\r|\n", "");
				;
				// 读取内容差异处理
				String[] content_p = content.split(params[5]);
				if (index < 3 && params.length < 11) {
					String tranDate = "";
					if (count(content_p[i - 1], params[8]) > 0) {
						tranDate = content_p[i - 1]
								.substring(content_p[i - 1].indexOf(params[8]) + params[8].length(),
										content.indexOf(params[8]) + params[8].length() + 20)
								.substring(0, 10).trim().replace("/", "-").replace("/", "-");
					} else {
						if(count(content, params[7]) > 0) {								
							tranDate = content
									.substring(content.indexOf(params[6]) + params[6].length(),
											content.indexOf(params[7]))
									.substring(0, 11).trim().replace("年", "-").replace("月", "-").replace("日", "");
						}else {
							tranDate = content
									.substring(content.indexOf(params[6]) + params[6].length(),content.indexOf(params[6]) + params[6].length() + 12)
									.substring(0, 11).trim().replace("年", "-").replace("月", "-").replace("日", "");
						}
					}
					if (count(content_p[i - 1], params[1]) > 1) {
						content_p[i - 1] = content_p[i - 1].split(params[0])[1];
					}
					String tranSeqNo = content_p[i - 1]
							.substring(content_p[i - 1].indexOf(params[1]) + params[1].length(),
									content_p[i - 1].indexOf(params[2]))
							.trim().replace("-", "") + ".pdf";

					//new File(savepath).renameTo(new File(path + File.separator + tranDate+"_"+ tranSeqNo));
					createPDF(savepath,path + File.separator + tranDate+"_"+ tranSeqNo);
					names.add(tranDate + "_" + tranSeqNo);
				} else {
					// String tranSeqNo =
					// content_p[n-i].substring(content_p[n-i].indexOf(params[1])+params[1].length()+1,content_p[n-i].indexOf(params[2])).trim().replace("-",
					// "");
					/*
					 * if(content_p[n-i].contains(params[4])) { fileName =
					 * content_p[n-i].substring(content_p[n-i].indexOf(params[3])+params[3].length()
					 * +1,content_p[n-i].indexOf(params[4])).trim()+".pdf"; } else { fileName =
					 * content_p[n-i].substring(content_p[n-i].indexOf(params[3])+params[3].length()
					 * +1,content_p[n-i].indexOf(params[1])).trim()+".pdf"; }
					 */
					if(!content_p[n - i].contains(params[13])) {
						continue;
					}
					String oppActNum = "";
					String amount = "";
					String oppActName = "";
					if (content_p[n - i].contains(params[6])) {
						if(content_p[n - i].contains(params[3])) {
							amount = content_p[n - i].substring(content_p[n - i].indexOf(params[6]) + params[6].length(),
									content_p[n - i].indexOf(params[3])).trim();
						}else{
							amount = content_p[n - i].substring(0,content_p[n - i].indexOf(params[6])).split("￥")[1];
						}
					} else {
						if (content_p[n - i].contains(params[15])) {
							amount = content_p[n - i].substring(content_p[n - i].indexOf(params[15]) - 13,
									content_p[n - i].indexOf(params[15])).trim().split("￥")[1];
						}  else if (content_p[n - i].contains(params[16])){
							amount = content_p[n - i].substring(content_p[n - i].indexOf(params[16]) - 13,
									content_p[n - i].indexOf(params[16])).trim().split("￥")[1];
						} else {
                            amount = content_p[n - i].substring(content_p[n - i].indexOf(params[18]) - 13,
                                    content_p[n - i].indexOf(params[18])).trim().split("￥")[1];
                        }
					}
					int codeIndex = content_p[n - i].indexOf(params[17]) + params[17].length();
					String receiptcode = content_p[n - i].substring(codeIndex, codeIndex + 13).trim();
					String trandate = content_p[n - i]
							.substring(content_p[n - i].indexOf(params[2]) + params[2].length() + 1,
									content_p[n - i].indexOf(params[2]) + params[2].length() + 12)
							.trim().substring(0, 10);
					String moneyway = content_p[n - i]
							.substring(content_p[n - i].indexOf(params[7]) + params[7].length(),
									content_p[n - i].indexOf(params[8]))
							.trim();
					if(moneyway.equals("贷")){
						oppActName = content_p[n - i]
								.substring(content_p[n - i].indexOf(params[19]) + params[19].length(),
										content_p[n - i].lastIndexOf(params[13]))
								.trim();
						oppActNum = content_p[n - i].split(params[14])[1];
					}else{
					 oppActName = content_p[n - i]
							.substring(content_p[n - i].lastIndexOf(params[11]) + params[11].length(),
									content_p[n - i].indexOf(params[12]))
							.trim();
					 oppActNum = content_p[n - i]
								.substring(content_p[n - i].indexOf(params[13]) + params[13].length(),
										content_p[n - i].indexOf(params[14]))
								.trim();
					}

					// file.renameTo(new File(path + File.separator + tranSeqNo +"_" + fileName));
					new File(savepath).renameTo(new File(path + File.separator + receiptcode + "_" + amount + "_"
							+ moneyway + "_" + trandate + "_" + oppActName + "_" + oppActNum + ".pdf"));
					//createPDF(savepath,path + File.separator + receiptcode + "_" + amount + "_" + moneyway + "_" + trandate + "_" + oppActName + "_" + oppActNum + ".pdf");
					names.add(receiptcode + "_" + amount + "_" + moneyway + "_" + trandate + "_" + oppActName + "_"
							+ oppActNum + ".pdf");
				}
			}

			return names;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} catch (DocumentException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (reader != null) {
				reader.close();
			}
			if (document != null) {
				document.close();
			}
			if (output != null) {
				output.close();
			}
			File desFile = new File(pdfFile);
			if (desFile.exists()) {
				desFile.delete();
			}
		}
	}
	
	/**
	   * 设置pdf样式
	 * @param path
	 * @param newPath
	 */
	public static void createPDF(String path,String newPath) {
		PdfDocument originalDoc = null;
		PdfDocument newDoc = null;
		try {
			originalDoc = new PdfDocument();
			originalDoc.loadFromFile(path);
			newDoc = new PdfDocument();
			//遍历所有PDF 页面  
	        Dimension2D dimension2D = new Dimension();  
	        for (int i = 0; i < originalDoc.getPages().getCount(); i++) {  
	            PdfPageBase page = originalDoc.getPages().get(i);             
	            if (i == 0) {   
	            	float scale = 1.0f;
	                float width = (float) page.getSize().getWidth();  
	                float height = (float) page.getSize().getHeight()*scale;  
	                dimension2D.setSize(width, height);  
	                PdfMargins margins = new PdfMargins(0,0);  
	                PdfPageBase newPage = newDoc.getPages().add(dimension2D, margins);  
	                //复制原文档的内容到新文档  
	                newPage.getCanvas().drawTemplate(page.createTemplate(), new Point2D.Float());  
	            }  
	            newDoc.saveToFile(newPath);  
	        }
	        originalDoc.close();
	        newDoc.close();
	        //删除临时文件
	        File file = new File(path);
	        if(file.exists()) {
	        	file.delete();
	        }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			if(originalDoc!=null) {
				originalDoc.close();
			}
			if(newDoc!=null) {
				newDoc.close();
			}
		}
	}


	public static boolean deleteFile(File dirFile) {
		// 如果dir对应的文件不存在，则退出
		if (!dirFile.exists()) {
			return false;
		}

		if (dirFile.isFile()) {
			return dirFile.delete();
		} else {

			for (File file : dirFile.listFiles()) {
				deleteFile(file);
			}
		}

		return dirFile.delete();
	}

    /**
     *
     * @param path PDF路径
     * @param width 表格宽度
     * @param height 表格高度
     * @return
     * @throws Exception
     */
    public static String readPDFTable(String path,int width, int height) throws Exception {
        PDDocument document = null;
        document = PDDocument.load(path);
        if (document.isEncrypted()) {
            try {
                document.decrypt("");
            } catch (Exception e) {
                System.err.println("Error: Document is encrypted with a password.");
                System.exit(1);
            }
        }
        PDFTextStripperByArea stripper = new PDFTextStripperByArea();
        stripper.setSortByPosition(true);
        java.awt.Rectangle rect = new java.awt.Rectangle(0, 0, width, height);
        stripper.addRegion("class1", rect);
        List allPages = document.getDocumentCatalog().getAllPages();
        PDPage firstPage = (PDPage) allPages.get(0);
        stripper.extractRegions(firstPage);
        return stripper.getTextForRegion("class1");
    }
}
